package com.leyou.user.service;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.exception.enums.ExceptionEnum;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.config.JwtProperties;
import com.leyou.user.dto.AddInfoDTO;
import com.leyou.user.dto.UserAddressDTO;
import com.leyou.user.entity.Area;
import com.leyou.user.entity.City;
import com.leyou.user.entity.Province;
import com.leyou.user.entity.UserAddress;
import com.leyou.user.mapper.UserAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 林琼杨
 * @version 1.0
 * @date 2020/5/27 19:08
 */
@Service
@Transactional
public class AddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private JwtProperties prop;

    /**
     * 加载所有省份
     * @param pid 省份id
     * @param cid 市级id
     * @return
     */
    public AddInfoDTO findAdds(String pid, String cid) {
        //创建对象
        AddInfoDTO addInfoDTO = new AddInfoDTO();
        //查询所有城市
        List<Province> provinceList = userAddressMapper.findProvince();
        List<City> cityList = userAddressMapper.findCity();
        List<Area> areaList = userAddressMapper.findArea();
        //封装数据
        addInfoDTO.setProvinces(provinceList);
        addInfoDTO.setCities(cityList);
        addInfoDTO.setAreas(areaList);
        return addInfoDTO;
    }

    /**
     * 当省级改变时加载市级
     * @param pid 省份id
     * @return
     */
    public List<City> loadCity(String pid) {
        List<City> cityList = userAddressMapper.loadCityByPid(pid);
        return cityList;
    }

    /**
     * 当市级改变时加载区级
     * @param cid 市级id
     * @return
     */
    public List<Area> loadArea(String cid) {
        List<Area> areaList = userAddressMapper.loadAreaByCid(cid);
        return areaList;
    }

    /**
     *  新增或修改收货地址
     * @param userAddressDTO 收货地址信息
     * @return
     */
    public void addUserAddress(HttpServletRequest request,UserAddressDTO userAddressDTO) {
        //校验用户
        //校验用户身份
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        Long userId = payload.getUserInfo().getId();
        UserAddress userAddress = BeanHelper.copyProperties(userAddressDTO, UserAddress.class);
        //插入数据
        if(userAddress.getId()==null){
            //创建
            userAddress.setUserId(userId);
            int count = userAddressMapper.insertSelective(userAddress);
            if(count!=1){
                throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
            }
        }else {
            //修改
            int count = userAddressMapper.updateByPrimaryKeySelective(userAddress);
            if(count!=1){
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

    }


    /**
     * 查询所有收货地址
     * @return
     */
    public List<UserAddressDTO> loadAddrList(HttpServletRequest request){
        //校验
        //校验用户身份
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        //获取用户id
        Long userId = payload.getUserInfo().getId();
        //封装用户id后 根据userId查询
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        List<UserAddress> userAddresses = userAddressMapper.select(userAddress);
        //转类型
        List<UserAddressDTO> userAddressDTOS = BeanHelper.copyWithCollection(userAddresses, UserAddressDTO.class);
        return userAddressDTOS;
    }

    /**
     * 删除地址
     * @param id 地址id
     * @return
     */
    public void delReceive(HttpServletRequest request,String id) {
        //校验用户身份
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        userAddressMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改为默认地址
     * @param id 地址id
     * @return
     */
    public void setDefault(HttpServletRequest request,String id) {
        //校验用户身份
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        //根据用户id 先查询所有地址，将地址全部设置为非默认地址 //其实可以让前端传一个old的id地址
        Long userId = payload.getUserInfo().getId();
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        List<UserAddress> addressList = userAddressMapper.select(userAddress);
        //遍历修改
        for (UserAddress address : addressList) {
            address.setIsDefault(false);
            userAddressMapper.updateByPrimaryKeySelective(address);
        }
        //设置默认地址
        UserAddress oldUserAddr = userAddressMapper.selectByPrimaryKey(id);
        oldUserAddr.setIsDefault(true);
        userAddressMapper.updateByPrimaryKeySelective(oldUserAddr);
    }

}
